package cn.wolfcode.exception;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*该类是针对控制器的增强
 *利用aop代理来实现增强
 * method:
 * */
@ControllerAdvice
public class CrmExceptionHandler {
    /*该方法用于捕获并处理某异常
     * 处理运行时异常
     * */

    @ExceptionHandler(RuntimeException.class)
    public String exceptionhandler(RuntimeException e, HandlerMethod method, HttpServletResponse response) {
        e.printStackTrace();//方便开发时找异常
        System.out.println("出异常了....");
        //如果原本控制器方法是返回jsonresult数据,现在出异常也应该返回jsonresult

        if (method.hasMethodAnnotation(ResponseBody.class)) {
            //使用response对象输出数据(json字符串)
            try {
                String msg = "操作失败,请联系管理员";
                if (e instanceof LogicException) {
                    msg = e.getMessage();
                }
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().print(JSON.toJSONString(new JsonResult(false, msg)));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return null;
        }
        //如果原本控制器的方法是返回视图页面,现在也应该会返回视图
        return "common/error";
    }

}
